package com.ilovepostcard;

import java.util.ArrayList;
import java.util.HashMap;

import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.ShareController;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.data.ReceiverInfo;
import com.ilovepostcard.data.SendTaskInfo;
import com.ilovepostcard.model.Address;
import com.ilovepostcard.model.NewOrderResult;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class PrintChooseAddressActivity  extends BaseActivity implements OnClickListener{
	
	ImageView mReturn;
	ListView addressList;
	Button confirm;  
	ImageView addAddress;
	Handler handler;
	boolean isSingle;
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_print_chooseaddress);
		init();
	}
	
	private void init()
	{
		handler = new Handler(); 
		addressList = (ListView)findViewById(R.id.address_list);
		final AddressListAdapter adapter = new AddressListAdapter();
		IServer server = ServerFactory.getServer();
		
		PostcardResult res = server.listAddress(UserController.getLoginUser(this).UserID, 1, 100);
		ArrayList<Address> address = res.getAddressList();
		for(int i =0;i<address.size();i++)
		{
			adapter.addAddress(address.get(i));
		}
		
		adapter.initSelectStatus();
		
		addressList.setAdapter(adapter);
		addressList.setItemsCanFocus(false);
		SendTaskInfo task = ShareController.getInstance().getCurrentSendTask();
		isSingle = task.isSingle;
		addressList.setChoiceMode(!isSingle? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_MULTIPLE);
		
		addressList.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(!isSingle)
				{
					adapter.setSelectedItem(arg2);
				}
				
			}
			
		}
		
		);
		mReturn = (ImageView)findViewById(R.id.title_return);
		mReturn.setOnClickListener(this);
		
		confirm = (Button)findViewById(R.id.confirm);
		confirm.setOnClickListener(this);
		
		addAddress = (ImageView)findViewById(R.id.title_add);
		addAddress.setOnClickListener(this);
		
		
	}
	
	
	class AddressListAdapter extends BaseAdapter
	{

		ArrayList<Address> list = new ArrayList<Address>();
		HashMap<Integer, Boolean> isSelected;
		int selectedIndex = -1;
		public void initSelectStatus()
		{
			isSelected = new HashMap<Integer, Boolean>(); 
			for (int i = 0; i < list.size(); i++) { 
				isSelected.put(i, false); 
			}
		}
		public void setAddress(ArrayList<Address> list)
		{
			this.list = list;
		}
		
		public void addAddress(Address a)
		{
			list.add(a);
		}
		
		public void setSelectedItem(int index)
		{
			selectedIndex = index;
			notifyDataSetInvalidated();
		}
		
		public int getSelectedIndex()
		{
			return selectedIndex;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}
		
		

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			if(convertView == null)
			{
				convertView = LayoutInflater.from(PrintChooseAddressActivity.this).inflate(R.layout.print_address_item, null);
			}
			TextView name = (TextView)convertView.findViewById(R.id.user_name);
			name.setText(list.get(position).Name);
			TextView phone = (TextView)convertView.findViewById(R.id.user_phone);
			phone.setText(list.get(position).Telephone);
			TextView zipcode = (TextView)convertView.findViewById(R.id.user_zipcode);
			zipcode.setText(list.get(position).Zipcode);
			TextView address = (TextView)convertView.findViewById(R.id.user_address);
			address.setText(list.get(position).Address);
			
			if(!isSingle)
			{
				RadioButton rb = (RadioButton)convertView.findViewById(R.id.address_checked_single);
				rb.setVisibility(View.VISIBLE);
				rb.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View v) {
						setSelectedItem(position);
						
					}
					
				});
				rb.setChecked(selectedIndex == position);
			}
			else
			{
				CheckBox cb = (CheckBox)convertView.findViewById(R.id.address_checked);
				cb.setVisibility(View.VISIBLE);
				//cb.setChecked(isSelected.get(position));
			}
			return convertView;
		}
		
	}


	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.title_return)
		{
			finish();
		}
		else if(v.getId() == R.id.confirm)
		{
			//SendTaskInfo task = ShareController.getInstance().getCurrentSendTask();
			/*if(!task.isSingle)
			{
				ArrayList<Long> checkAddress = new ArrayList<Long>();
    			
    			for (int i = 0; i < addressList.getChildCount(); i++) {
    			     LinearLayout ll = (LinearLayout)addressList.getChildAt(i);
    			     CheckBox check = (CheckBox) ll.findViewById(R.id.address_checked);
    			     
    			     if(check.isChecked())
    			    	 checkAddress.add(((Address)addressList.getItemAtPosition(i)).FAID);
    			}
    			checkAddress.trimToSize();
    			if(checkAddress.size()!=1)
    			{
    				Toast.makeText(this, "套装只能寄送给一个地址哦!", Toast.LENGTH_SHORT).show();
    				return;
    			}
			}
			*/
			new ServerAsyncTask(this,false) {
	            
	            @Override
	            protected void onSuccess(PostcardResult result) {
	            	if(result == null || !result.isSuccess())
	    			{
	    				if(result!= null)
	    					Toast.makeText(PrintChooseAddressActivity.this, "支付结果:"+result.isSuccess()+", 错误信息:"+result.getErrorMsg(PrintChooseAddressActivity.this), Toast.LENGTH_SHORT).show();
	    				else
	    					Toast.makeText(PrintChooseAddressActivity.this, "支付结果: false"+", 错误信息: unknow", Toast.LENGTH_SHORT).show();
	    			}
	    			else
	    			{
	    				NewOrderResult res = result.getNewOrderResult();
	    				if(res == null)
	    				{
	    					Toast.makeText(PrintChooseAddressActivity.this, "服务器错误", Toast.LENGTH_SHORT).show();
	    					Intent intent = new Intent(PrintChooseAddressActivity.this,MainActivity.class);
	    					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    					PrintChooseAddressActivity.this.startActivity(intent);
	    					return;
	    				}

	    				String url = res.PayUrl;
	    				Intent nextPage = new Intent(PrintChooseAddressActivity.this,EmptyActivity.class);
	    				Bundle extras = new Bundle();
	    				extras.putLong("id", res.OrderID);
	    				extras.putString("url", url);
	    				extras.putBoolean("type", true);
	    				nextPage.putExtras(extras);
	    				PrintChooseAddressActivity.this.startActivity(nextPage);
	    			}
	            }
	            
	            @Override
	            protected PostcardResult doRequest() {
	            	 IServer server = ServerFactory.getServer();
	    			 SendTaskInfo task = ShareController.getInstance().getCurrentSendTask();
	    			
	    			ArrayList<Postcard>  pcList = task.postcardList;
	    			
	    			long[] pids = new long[pcList.size()];
	    			for(int i =0;i<pids.length;i++)
	    				pids[i] = pcList.get(i).id;
	    			
	    			ArrayList<Long> checkAddress = new ArrayList<Long>();
	    			
	    			if(isSingle)
	    			{
	    				for (int i = 0; i < addressList.getChildCount(); i++) {
		    			     LinearLayout ll = (LinearLayout)addressList.getChildAt(i);
		    			     CheckBox check = (CheckBox) ll.findViewById(R.id.address_checked);
		    			     
		    			     if(check.isChecked())
		    			    	 checkAddress.add(((Address)addressList.getItemAtPosition(i)).FAID);
		    			}
	    			}
	    			else
	    			{
	    				AddressListAdapter adapter = (AddressListAdapter)addressList.getAdapter();
	    				int index = adapter.getSelectedIndex();
	    				checkAddress.add(((Address)adapter.getItem(index)).FAID);
	    			}
	    			
	    			checkAddress.trimToSize();
	    			
	    			if(checkAddress.size() == 0)
	    			{
	    				handler.post(new Runnable()
	    				{

							@Override
							public void run() {
								Toast.makeText(PrintChooseAddressActivity.this, "请选择联系人", Toast.LENGTH_SHORT).show();
								
							}
	    					
	    				});
	    				
	    				return null;
	    			}
	    			else
	    			{
	    				long[] aids = new long[checkAddress.size()];
		    			for(int i = 0; i < checkAddress.size(); i++)
		    				aids[i] = checkAddress.get(i).longValue();
		                return server.newOrder(task.isSingle? "single" : "suit", UserController.getLoginUser(PrintChooseAddressActivity.this).UserID, pids, task.comment, aids);
	    			}
	    			
	            }
	        }.execute();
	        
			/*PostcardResult result = server.newOrder(task.isSingle? "single" : "suit", UserController.getLoginUser(this).UserID, pids, task.comment, aids);
			if(result == null || !result.isSuccess())
			{
				if(result!= null)
					Toast.makeText(this, "支付结果:"+result.isSuccess()+", 错误信息:"+result.getErrorMsg(this), Toast.LENGTH_SHORT).show();
				else
					Toast.makeText(this, "支付结果: false"+", 错误信息: unknow", Toast.LENGTH_SHORT).show();
			}
			else
			{
				NewOrderResult res = result.getNewOrderResult();
				String url = res.PayUrl;
				Intent nextPage = new Intent(this,EmptyActivity.class);
				Bundle extras = new Bundle();
				extras.putLong("id", res.OrderID);
				extras.putString("url", url);
				nextPage.putExtras(extras);
				PrintChooseAddressActivity.this.startActivity(nextPage);
			}*/
		}
		else if(v.getId() == R.id.title_add)
		{
			Intent nextPage = new Intent(PrintChooseAddressActivity.this,PrintAddressActivity.class);
			PrintChooseAddressActivity.this.startActivity(nextPage);
		}
	}

}
